package modele.dao;

import java.sql.SQLException;
import java.util.ArrayList;

import modele.beans.Key;
import modele.database.IDatabase;

public class KeyDAO {
	private IDatabase conn;
	
	public KeyDAO(IDatabase conn) {
		this.conn = conn; 
	}
	
	public ArrayList<Key> GetKeys() throws SQLException, ClassNotFoundException {
		conn.Connect();
		ArrayList<ArrayList<Object>> keyList = conn.Select("SELECT NAME, DESCRIPTION, KEY_ID FROM KEY");
		
		ArrayList<Key> keys = new ArrayList<Key>();
		
		for (int i = 0; i != keyList.size(); ++i) {
			keys.add(new Key((String)keyList.get(i).get(0),
					(String)keyList.get(i).get(1),
					keyList.get(i).get(2).toString()));
		}
		
		conn.Close();
		
		return keys;
	}
	
	public void AddKey(Key key) throws SQLException, ClassNotFoundException {
		conn.Connect();
		conn.Insert("INSERT INTO KEY(NAME, DESCRIPTION, KEY_ID) "
					+ " SELECT ?, ?, key_seq.nextval FROM DUAL", key.getName(), key.getDescription());
		conn.Close();
	}
	
	public void UpdateKey(Key key) throws SQLException, ClassNotFoundException {
		conn.Connect();
		conn.Update("UPDATE KEY " +
					" SET NAME = ?, " +
					" DESCRIPTION = ? " +
					" WHERE KEY_ID = ?", key.getName(), key.getDescription(), key.getId());
		conn.Close();
	}
	
	public void RemoveKey(Key key) throws SQLException, ClassNotFoundException {
		conn.Connect();
		conn.Update("DELETE FROM KEY " +
					" WHERE KEY_ID = ? ", key.getId());
		conn.Close();
	}
}
